package com.zhixing.controller;

import com.zhixing.common.TemplateContentFactory;
import com.zhixing.model.SwaggerAPI;
import com.zhixing.service.executor.SwaggerExecutor;
import com.zhixing.service.executor.SwaggerExecutorFactory;
import com.zhixing.utils.FileDownloadUtil;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.Model;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

import static com.zhixing.common.IConstants.SYMBOL_EN_COMMA;

/**
 * swagger 2 word API
 *
 * 接口定义
 * @author zhixing
 */
@NoArgsConstructor
@AllArgsConstructor
public class SimpleSwagger2WordProcessor implements ISwagger2WordProcessor {

    @Setter
    private RestTemplate            restTemplate;

    @Setter
    private SpringTemplateEngine    templateEngine;

    @Override
    public String getWord(Model model, String url, String tags) {
        // 构建模板渲染数据
        generateModelData(model, url,tagsProcess(tags));
        // 返回模板名称
        return TemplateContentFactory.TemplateContentType.WORD_1.getFileName();
    }

    @Override
    public void word(Model model, String url, String fileName, String tags, HttpServletResponse response) {
        // 构建模板渲染数据
        generateModelData(model, url, tagsProcess(tags));

        // 加载模板进行下载
        Context context = new Context();
        context.setVariables(model.asMap());
        String templateContent = TemplateContentFactory.getTemplateContent(TemplateContentFactory.TemplateContentType.WORD_1, context,templateEngine);
        FileDownloadUtil.writeToResponse(templateContent,response,fileName);
    }

    protected List<String> tagsProcess(String tags){
        List<String> includeTagsList = new ArrayList<>();
        if(StringUtils.isNotBlank(tags) ){
            String[] tagsArray = tags.split(SYMBOL_EN_COMMA);
            if(null != tagsArray && tagsArray.length > 0){
                includeTagsList = Arrays.asList(tags);
            }
        }
        return includeTagsList;
    }

    private void generateModelData(Model model, String url,List<String> includeTags) {
        SwaggerExecutor swaggerExecutor = SwaggerExecutorFactory.getInstance(includeTags, restTemplate.getForObject(url, String.class));
        Map<String,Object> resultMap = new HashMap<>();
        Map<String, List<SwaggerAPI>> tableMap = swaggerExecutor.getApiResultList().stream().parallel().collect(Collectors.groupingBy(SwaggerAPI::getTitle));
        resultMap.put("tableMap", new TreeMap<>(tableMap));
        resultMap.put("info", swaggerExecutor.getAllResultMap().get("info"));
        model.addAllAttributes(resultMap);
    }
}
